# user.py
from flask import Blueprint, render_template, jsonify, request, current_app
from flask_login import login_required, current_user
from flask_socketio import emit
from .app import db, socketio
from .models import Feedback, User, AdminRequest, FeedbackResponse, Announcement, Survey, SurveyResponse
from datetime import datetime
from functools import partial

user_bp = Blueprint('user', __name__)

@user_bp.route('/dashboard')
@login_required
def dashboard():
    return render_template('dashboard.html')

@user_bp.route('/api/announcements')
@login_required
def get_announcements():
    announcements = Announcement.query.order_by(Announcement.created_at.desc()).all()
    return jsonify([{
        'id': a.id,
        'title': a.title,
        'content': a.content,
        'created_at': a.created_at.strftime('%Y-%m-%d %H:%M')
    } for a in announcements])

@user_bp.route('/api/surveys')
@login_required
def get_surveys():
    surveys = Survey.query.order_by(Survey.created_at.desc()).all()
    return jsonify([{
        'id': s.id,
        'title': s.title,
        'content': s.content,
        'created_at': s.created_at.strftime('%Y-%m-%d %H:%M')
    } for s in surveys])

@user_bp.route('/api/surveys/<int:survey_id>/responses', methods=['POST'])
@login_required
def create_survey_response(survey_id):
    data = request.get_json()
    survey = Survey.query.get(survey_id)
    if not survey:
        return jsonify({'success': False, 'message': '问卷不存在'}), 404
    
    # 使用 response 字段名
    new_response = SurveyResponse(
        survey_id=survey_id,
        user_id=current_user.id,
        response=data['content']  # 注意字段名改为 response
    )
    db.session.add(new_response)
    db.session.commit()
    
    socketio.emit('new_survey_response', {
        'id': new_response.id,
        'survey_id': survey_id,
        'user_id': current_user.id,
        'username': current_user.username,
        'content': new_response.response,  # 使用 response 字段
        'created_at': new_response.created_at.strftime('%Y-%m-%d %H:%M')
    }, broadcast=True)
    
    return jsonify({'success': True, 'id': new_response.id})

@user_bp.route('/api/feedbacks', methods=['POST'])
@login_required
def create_feedback_api():
    data = request.get_json()
    new_feedback = Feedback(
        user_id=current_user.id,
        content=data['content']
    )
    db.session.add(new_feedback)
    db.session.commit()
    
    socketio.emit('new_feedback', {
        'id': new_feedback.id,
        'user_id': current_user.id,
        'username': current_user.username,
        'content': new_feedback.content,
        'created_at': new_feedback.created_at.strftime('%Y-%m-%d %H:%M')
    }, broadcast=True)
    
    return jsonify({'success': True, 'id': new_feedback.id})

@user_bp.route('/api/my_feedbacks')
@login_required
def get_my_feedbacks():
    try:
        # 获取当前用户的所有反馈
        feedbacks = Feedback.query.filter_by(user_id=current_user.id).order_by(Feedback.created_at.desc()).all()
        
        feedbacks_with_responses = []
        for f in feedbacks:
            responses = FeedbackResponse.query.filter_by(feedback_id=f.id).order_by(FeedbackResponse.created_at.asc()).all()
            feedbacks_with_responses.append({
                'id': f.id,
                'content': f.content,
                'status': f.status,
                'created_at': f.created_at.strftime('%Y-%m-%d %H:%M'),
                'responses': [{
                    'content': r.content,
                    'created_at': r.created_at.strftime('%Y-%m-%d %H:%M')
                } for r in responses]
            })
        
        return jsonify(feedbacks_with_responses)
    
    except Exception as e:
        # 使用 current_app.logger 記錄錯誤會更健壯
        current_app.logger.error(f"获取用户反馈失败: {str(e)}")
        return jsonify({'success': False, 'message': f'获取反馈失败: {str(e)}'}), 500

# user.py
@user_bp.route('/api/feedbacks/<int:feedback_id>')
@login_required
def get_feedback_detail(feedback_id):
    try:
        # 获取反馈详情
        feedback = db.session.get(Feedback, feedback_id)
        if not feedback:
            return jsonify({'success': False, 'message': '反馈不存在'}), 404
        
        # 恢复权限检查
        if int(feedback.user_id) != int(current_user.id):
            if getattr(current_user, 'role', 'user') != '管理员':
                return jsonify({'success': False, 'message': '权限不足'}), 403

        # 获取所有回复
        responses = FeedbackResponse.query.filter_by(feedback_id=feedback_id).order_by(FeedbackResponse.created_at.desc()).all()
        
        return jsonify({
            'id': feedback.id,
            'content': feedback.content,
            'status': feedback.status,
            'created_at': feedback.created_at.strftime('%Y-%m-%d %H:%M'),
            'responses': [{
                'id': r.id,
                'content': r.content,
                'created_at': r.created_at.strftime('%Y-%m-%d %H:%M')
            } for r in responses]
        })
    
    except Exception as e:
        current_app.logger.error(f"获取反馈详情失败: {str(e)}")
        return jsonify({'success': False, 'message': f'获取反馈详情失败: {str(e)}'}), 500
    
@user_bp.route('/api/admin_requests', methods=['POST'])
@login_required
def create_admin_request():
    data = request.get_json()
    new_request = AdminRequest(
        user_id=current_user.id,
        reason=data['reason'],
        status='pending'
    )
    db.session.add(new_request)
    db.session.commit()
    
    socketio.emit('new_admin_request', {
        'id': new_request.id,
        'user_id': current_user.id,
        'username': current_user.username,
        'reason': new_request.reason,
        'created_at': new_request.created_at.strftime('%Y-%m-%d %H:%M')
    }, broadcast=True)
    
    return jsonify({'success': True, 'id': new_request.id})

@user_bp.route('/api/my_admin_requests')
@login_required
def get_my_admin_requests():
    requests = AdminRequest.query.filter_by(user_id=current_user.id).order_by(AdminRequest.created_at.desc()).all()
    return jsonify([{
        'id': r.id,
        'user_id': r.user_id,
        'reason': r.reason,
        'status': r.status,
        'created_at': r.created_at.strftime('%Y-%m-%d %H:%M')
    } for r in requests])